﻿#region Copyright (C) Sector7 Software Studio. All rights reserved
/*******************************************************************************************
 * Creation
 *      Author:         Wolf Lai
 *      Date:           2012/3/15 21:03:17
 *      Version:        
 * Modification 
 *      Author: 
 *      Date: 
 *      Description: 
 *      Version:
 *******************************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Linq.Expressions;
using Sector7.Framework.Core;
using Sector7.Framework.Enums;
using Sector7.Framework.Consts;

namespace Sector7.Framework.Utility
{
    /// <summary>
    /// WCF客户端工具类
    /// </summary>
    /// <typeparam name="TService">契约类型</typeparam>
    public class WcfClientUtil<TService> where TService : class
    {
        #region Public functions
        /// <summary>
        /// 调用方法
        /// </summary>
        /// <typeparam name="TReturn">返回值类型</typeparam>
        /// <param name="operation">方法名称</param>
        /// <returns></returns>
        public TReturn Invoke<TReturn>(Expression<Func<TService, TReturn>> operation)
        {
            var channelFactory = new ChannelFactory<TService>("*");

            TService channel = channelFactory.CreateChannel();
            var client = (IClientChannel)channel;

            client.Open();

            TReturn result = default(TReturn);

            try
            {
                result = operation.Compile().Invoke(channel);

                if (client.State != CommunicationState.Faulted)
                    client.Close();
                else
                    client.Abort();
            }
            catch(Exception e)
            {
                Log.WriteLine(LogSeverityType.ERR, C_ModuleName.FRAMEWORK, e);
                client.Abort();
            }

            return result;
        }
        #endregion
    }
}
